<template>
  <div>

    <div style="margin-bottom: 15px">
      <el-input style="width: 200px; margin-right: 5px" v-model="params.deviceName" placeholder="请输入设备名称"></el-input>
      <el-input style="width: 200px" v-model="params.location" placeholder="请输入设备位置"></el-input>
      <el-button type="warning" style="margin-left: 10px" size="small" @click="findBySearchOfDevices()">查询</el-button>
      <el-button type="info" style="margin-left: 10px" size="small" @click="reset()">清空</el-button>
      <el-button v-if="user.identity !=='孩子' " type="primary" style="margin-left: 10px" size="small" @click="add()">新增
      </el-button>
    </div>
    <!--    主体表格-->
    <div>
      <el-table :data="tableData" style="width: 100%" :row-style="{ height: '80px' }">
        <el-table-column v-if="user.identity !== '孩子'" prop="deviceId" label="设备编号" width="180"></el-table-column>
        <el-table-column prop="deviceName" label="设备名称" width="180"></el-table-column>
        <el-table-column v-if="user.identity !== '孩子'" prop="deviceType" label="设备类别"></el-table-column>
        <el-table-column prop="status" label="设备状态">
          <template slot-scope="scope">
            <div :style="{ color: scope.row.status === '0' ? 'red' : 'green' }">
              {{ scope.row.status === '0' ? '关闭' : '开启' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="controlMode" label="运行模式">
          <template slot-scope="scope">
            <div>
              {{ scope.row.controlMode === 'A' ? '自动模式' : '手动模式' }}
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="threshold" label="阈值设置"></el-table-column>-->
        <el-table-column prop="location" label="设备位置"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button style="margin-right: 5px" size="small" type="primary" @click="edit(scope.row)" :disabled="!canEditDevice(scope.row)">编辑</el-button>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="remove(scope.row.deviceId)">
              <el-button v-if="user.identity !== '孩子'" slot="reference" size="small" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--    新增编辑对话框-->
    <el-dialog title="请填写信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item v-if="user.identity !== '孩子'" label="设备编号" label-width="15%">
          <el-input v-model="form.deviceId" autocomplete="off" style="width: 90%" placeholder="例如：AC_01"></el-input>
        </el-form-item>
        <el-form-item v-if="user.identity !== '孩子'" label="设备名称" label-width="15%">
          <el-input v-model="form.deviceName" autocomplete="off" style="width: 90%" placeholder="例如：客厅空调"></el-input>
        </el-form-item>
        <el-form-item v-if="user.identity !== '孩子'" label="设备类别" label-width="15%">
          <el-input v-model="form.deviceType" autocomplete="off" style="width: 90%" placeholder="例如：AC"></el-input>
        </el-form-item>
        <el-form-item label="设备状态" label-width="15%" style="width: 90%">
          <el-radio v-model="form.status" label="0">关闭</el-radio>
          <el-radio v-model="form.status" label="1">开启</el-radio>
        </el-form-item>
        <el-form-item label="控制模式" label-width="15%" style="width: 90%">
          <el-radio v-model="form.controlMode" label="A">自动模式</el-radio>
          <el-radio v-model="form.controlMode" label="M" >手动模式</el-radio>
        </el-form-item>
        <el-form-item label="阈值设置" label-width="15%" style="width: 90%">
          <el-input-number size="small" controls-position="right" v-model="form.threshold" @change="handleChange"
                           label="阈值"></el-input-number>
          <span v-if="form.deviceType === 'AC'">℃</span>
          <span v-else-if="form.deviceType === 'CURTAIN' || form.deviceType === 'LED'">Lux</span>
        </el-form-item>
        <el-form-item v-if="user.identity !== '孩子'" label="设备位置" label-width="15%" style="width: 90%">
          <el-input v-model="form.location" autocomplete="off" placeholder="例如：客厅"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>

    <!--    分页功能-->
    <div style="margin-top: 15px; text-align: center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page=params.pageNum
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
  </div>

</template>

<script>
import request from "@/utils/request";

export default {
  name: 'Common_Devices',
  data() {
    return {
      tableData: [],
      params: {
        deviceName: '',
        location: '',
        threshold: '',
        pageNum: 1,
        pageSize: 5,
      },
      form: {},
      total: 0,
      dialogFormVisible: false,
      //将登录用户信息取出
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
    }

  },
  created() {
    this.findBySearchOfDevices();
  },
  methods: {
    //前后台连接测试
    findAll() {
      request.get("/Devices/findAll").then(res => {
        if (res.code === '0') {
          this.tableData = res.data;

        } else {

        }
      })
    },
    findBySearchOfDevices() {
      request.get("Devices/findBySearchOfDevices", {params: this.params}).then(res => {
        if (res.code === '0') {
          this.tableData = res.data.list;
          this.total = res.data.total;
        } else {

        }
      })
    },
    reset() {
      this.params = {
        deviceName: '',
        location: '',
        pageNum: 1,
        pageSize: 5
      }
      this.findBySearchOfDevices();
    },
    add() {
      this.form = {}; //清空表单信息
      this.dialogFormVisible = true;
    },
    submit() {
      request.post("/Devices/addDevice", this.form).then(res => {
        console.log("编辑的内容；", this.form);
        if (res.code === '0') {
          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.findBySearchOfDevices();
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    remove(deviceId) {
      request.delete("Devices/deleteDevice/" + deviceId).then(res => {
        if (res.code === '0') {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.findBySearchOfDevices();
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    edit(data) {
      this.form = data;
      this.dialogFormVisible = true;
    },
    canEditDevice(device) {
      const currentUser = this.user;

      // admin 可以编辑所有设备
      if (currentUser.identity === 'admin') {
        return true;
      }

      // 非admin，查看是否包含该设备权限
      const allowedDeviceIds = currentUser.deviceIds || [];
      return allowedDeviceIds.includes(device.deviceId);
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.findBySearchOfDevices();
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum;
      this.findBySearchOfDevices();
    },
    handleChange(threshold) {
      this.params.threshold = threshold;
    }
  },
}
</script>